package com.itaming.lycheeframework.logging.bootstrap;

import com.itaming.lycheeframework.bootstrap.EnvironmentProcessor;
import com.itaming.lycheeframework.support.utils.StringUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * Logging模块环境处理器
 *
 * @author A.Ming
 */
public class LycheeLoggingEnvironmentProcessor implements EnvironmentProcessor, Ordered {

    /**
     * 日志配置文件属性名称
     */
    private static final String LOGGING_CONFIG_PROPERTY_NAME = "logging.config";

    /**
     * 处理环境
     *
     * @param environment 环境对象
     * @param application 应用对象
     */
    @Override
    public void process(ConfigurableEnvironment environment, SpringApplication application) {
        // 获取外部指定的Logback配置文件
        String loggingConfig = environment.getProperty(LOGGING_CONFIG_PROPERTY_NAME);

        // 如果外部未指定，则使用默认配置
        if (StringUtil.isBlank(loggingConfig)) {
            String activeProfile = getActiveProfile(environment);
            loggingConfig = "classpath:logback/logback-" + activeProfile + ".xml";
            environment.getSystemProperties().put(LOGGING_CONFIG_PROPERTY_NAME, loggingConfig);
        }
    }

    /**
     * 获取当前激活的profile
     *
     * @param environment 环境
     * @return 当前激活的profile
     */
    private String getActiveProfile(ConfigurableEnvironment environment) {
        String[] activeProfiles = environment.getActiveProfiles();
        return activeProfiles.length == 0 ? environment.getDefaultProfiles()[0] : activeProfiles[activeProfiles.length - 1];
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }

}
